import { MethodMetaContext } from './Meta';
import HashMap from '@ohos.util.HashMap';

export class Utils {
  static formatString(str: string, ...args: any): string {
    let pos = 0
    return str.replace(/\{(\s*)\}/g, (match, index) => {
      const text = args[0][pos]
      const ret = typeof text !== "undefined" ? text : match;
      pos++
      return ret;
    });
  }

  static parameterError(method: MethodMetaContext, p: number, message, ...args) {
    Utils.methodError(method, "", message + " (parameter #" + (p + 1) + ")", args)
  }

  static methodError(method: MethodMetaContext, cause, message, ...args) {
    message = this.formatString(message, args);
    return new Error(
      message
        + "\n    for function "
        + method.target
        + "."
        + method.methodName
        + ":"
        + cause
    );
  }

  static isEmpty(text: string) {
    return Utils.isUndefined(text) || !text || text.length == 0
  }

  static isHttpOrHttps(str: string): boolean {
    const regex = new RegExp("^(http[s]?://)")
    return regex.test(str);
  }

  static formatUrl(
    baseUrl: string,
    relativeUrl: string,
    queryMapping: HashMap<string, any>
  ): string {
    if (!baseUrl) {
      baseUrl = ""
    }

    if (!relativeUrl) {
      relativeUrl = ""
    }
    if (!baseUrl.endsWith('/')) {
      baseUrl = baseUrl + '/'
    }

    if (relativeUrl.startsWith('/')) {
      relativeUrl = relativeUrl.slice(1)
    }
    let url = baseUrl + relativeUrl

    const query = this.buildQueryParameter(queryMapping)
    if (!this.isEmpty(query)) {
      if (url.endsWith('/')) {
        url = url.slice(0, -1)
      }
    }
    return url + query
  }

  static buildQueryParameter(queryMapping: HashMap<string, any>): string {
    const size = queryMapping.length
    if (size == 0) {
      return ''
    }
    let query = '?'
    let index = 0
    queryMapping.forEach((v, k) => {
      query += k + "=" + v
      if (index != size - 1) {
        query += '&'
      }
      index++
    })
    return query
  }

  static isUndefined(value: any) {
    return typeof value === 'undefined'
  }
}